package com.doyens.gmall.product.controller;

import com.doyens.gmall.common.result.Result;
import io.swagger.annotations.Api;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Classname:FileUploadController
 * PackageName:com.doyens.gmall.product.controller
 *
 * @Author:uyijk
 * @Create:2023/7/26 15:38
 * @Version: 1.0
 */
@RestController
@RequestMapping("admin/product")
@Api(tags = "上传文件到fastDFS")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String url;
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws MyException, IOException {
        //上传到fastDFS中
        //读取配置文件
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        String path = null;
        if(configFile!=null){
            //初始化上传参数（主服务器地址）
            ClientGlobal.init(configFile);
            //创建本地客户端对象
            TrackerClient trackerClient = new TrackerClient();
            //连接主服务器
            TrackerServer trackerServer = trackerClient.getConnection();
            //从主服务器获取可用的从服务器地址，为了上传
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            //上传文件到从服务器，会返回文件的存储路径
            path = storageClient1.upload_appender_file1(file.getBytes(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        }
        return Result.ok(url+path);

    }

}
